/*
 * @Author: lbt666 '1319451895@qq.com'
 * @Date: 2022-07-28 16:33:42
 * @LastEditors: lbt666 '1319451895@qq.com'
 * @LastEditTime: 2023-02-24 14:14:32
 * @Description: 
 */
import { createI18n } from 'vue-i18n'
import { Locale } from 'vant';
import enUS from 'vant/lib/locale/lang/en-US'
import zhCN from 'vant/lib/locale/lang/zh-CN'

import enLocale from './en_us'
import zhLocale from './zh_cn'


const messages = {
  en: {
    ...enUS,
    ...enLocale
  },
  zh: {
    ...zhCN,
    ...zhLocale
  }
}

let nowSettingLanguage = ''
if (localStorage.getItem('language')) {
  nowSettingLanguage = (localStorage.getItem('language') as string)
  vantLocales(nowSettingLanguage)
} else {
  const language = navigator.language
  switch (language.toLowerCase()) {
    case 'zh-cn':
      nowSettingLanguage = 'zh'
      break
    case 'en-us':
      nowSettingLanguage = 'en'
      break
    default:
      nowSettingLanguage = 'zh'
      break
  }
  vantLocales(nowSettingLanguage)
}

localStorage.setItem('language', nowSettingLanguage)
export const i18n = createI18n({
  legacy: false, // 让 setup 函数可以通过 t 访问
  globalInjection: true, // 让 template 可以像 vue2 那样使用 $t 来访问
  locale: nowSettingLanguage, // 设置默认语言
  messages: messages, // 设置资源文件对象
  fallbackLocale: 'zh' // 没有其他语言的情况下默认中文
})

// 更新vant组件库本身的语言变化，支持国际化
export function vantLocales(lang: string) {
  if (lang === 'en') {
    Locale.use(lang, enUS)
  } else if (lang === 'zh') {
    Locale.use(lang, zhCN)
  }
}

export function i18nText(val: string, obj: any) {
  try {
    const { t } = i18n.global
    return t(val, obj)
  } catch (error) {
    console.log(error);
  }
}